package cn.dlc.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import com.licheedev.myutils.LogPlus;
import io.reactivex.Observable;
import io.reactivex.subjects.ReplaySubject;
import io.reactivex.subjects.Subject;
import java.util.List;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 启动页面
 */
public class EasyPermHelper implements EasyPermissions.PermissionCallbacks {
    
    private final Activity mActivity;
    private final Observable<Boolean> mResultObservable;
    private final int mRequestCode;

    private Subject<Boolean> mSubject;
    private String[] mPermissions;
    private List<String> mDeniedPermissions;
    private final Handler mHandler;

    public EasyPermHelper(Activity activity, @NonNull String[] permissions, int requestCode) {

        mActivity = activity;
        mPermissions = permissions;
        mRequestCode = requestCode;
        mHandler = new Handler(Looper.getMainLooper());

        mSubject = ReplaySubject.<Boolean>create().toSerialized();
        mResultObservable = mSubject.hide();
    }

    public Observable<Boolean> rxResult() {
        return mResultObservable;
    }

    private void checkPermissions(long delay) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                checkPermissions();
            }
        }, delay);
    }

    public void checkPermissions() {

        if (EasyPermissions.hasPermissions(mActivity, mPermissions)) {
            // 拿全权限，发射ok
            mSubject.onNext(true);
            mSubject.onComplete();
        } else if (mDeniedPermissions != null && EasyPermissions.somePermissionPermanentlyDenied(
            mActivity, mDeniedPermissions)) {
            new AppSettingsDialog.Builder(mActivity).setTitle("请求权限")
                .setRationale("部分权限获取失败，APP无法正常运行。请在设置页面为应用手动添加权限。")
                .build()
                .show();
        } else {
            //权限拒绝 申请权限
            mDeniedPermissions = null;
            EasyPermissions.requestPermissions(mActivity, "为确保APP正常运行，请允许下列权限", mRequestCode,
                mPermissions);
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            // Do something after user returned from app settings screen, like showing a Toast.
            checkPermissions(500);
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions,
        int[] grantResults) {
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        LogPlus.e("Granted-requestCode=" + requestCode + ",perms=" + perms);
        if (perms.size() == mPermissions.length) {
            checkPermissions(200);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        LogPlus.e("Denied-requestCode=" + requestCode + ",perms=" + perms);
        mDeniedPermissions = perms;
        checkPermissions(200);
    }
}
